/**
 * @filename RechargeController.java
 */
package com.liupf.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.util.PathUtil;
import com.liupf.common.utils.Constants;
import com.liupf.common.utils.PushTokenUtils;
import com.liupf.common.utils.PushTokenUtils.JpushType;
import com.liupf.common.utils.SmsUtil;
import com.liupf.common.utils.TimeUtil;
import com.liupf.common.utils.TypeConstant;
import com.liupf.domain.Driver;
import com.liupf.domain.Recharge;

/**
 * @description 代驾员充值操作
 * @author shevliu
 * @email shevliu@gmail.com Jul 29, 2012 10:04:10 PM
 */
public class RechargeController extends Controller {

	private Log log = LogFactory.getLog(this.getClass());

	public void index() {
		String job_number = getPara("job_number");
		String realName = getPara("real_name");
		String cellPhone = getPara("cell_phone");
		String beginDateStr = getPara("start_time");
		String endDateStr = getPara("end_time");
		

		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);
		
		String company=(String) getSession().getAttribute("company");
		
//		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		StringBuffer from = new StringBuffer();
		from.append(" from recharge a inner join b_user b on a.b_user_id = b.id left join sys_user c on a.sys_user_id = c.id where 1=1");
		if (StringUtils.isNotBlank(job_number)) {
			from.append(" and b.job_number='" + job_number.toUpperCase() + "'");
		}
		if (StringUtils	.isNotBlank(realName)) {
			from.append(" and b.name='" + realName + "'");
		}
		if (StringUtils.isNotBlank(cellPhone)) {
			from.append(" and b.phone='" + cellPhone + "'");
		}
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			from.append(" and b.job_number regexp '" + company + "[0-9]+'");
		}
		if(StringUtils.isNotEmpty(beginDateStr) && StringUtils.isNotEmpty(endDateStr)){
			//from.append(" and a.time >"+beginDateStr+" and a.time<"+endDateStr);
			from.append(" and a.time  between '"+TimeUtil.format(beginDate, "yyyy-MM-dd HH:mm:ss")+"' and '"+TimeUtil.format(endDate, "yyyy-MM-dd HH:mm:ss")+"'");
		}
		
		from.append(" order by a.id DESC ");
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select b.id,b.login_name, b.job_number , b.name,b.phone ,a.before_balance, a.money , a.recharge_type  , a.time , c.real_name as sysUserName",
						from.toString());
		
		System.out.println("select b.login_name, b.job_number , b.name,b.phone , a.money , a.recharge_type  , a.time , c.real_name as sysUserName " + from.toString());
		
		setAttr("page", page);
		// 保存查询条件到页面
		setAttr("job_number", job_number);
		setAttr("real_name", realName);
		setAttr("cell_phone", cellPhone);
		setAttr("start_time", beginDateStr);
		setAttr("end_time", endDateStr);

		render("recharge_list.ftl");
	}

	public void add() {
		int driverId = getParaToInt();
		Driver driver = Driver.dao.findById(driverId);
		setAttr("driver", driver);
		render("../recharge/driver_recharge.ftl");
	}

	@Before(Tx.class)
	public void save() {
		Recharge recharge = getModel(Recharge.class);
		int driverId = recharge.getInt("b_user_id");
		int sysUserId = (Integer) getSession().getAttribute("userId");
		recharge.put("sys_user_id", sysUserId);
		recharge.put("time", new Date());
		recharge.put("status", 1);
		
		Driver driver = Driver.dao.findById(driverId);
		BigDecimal preIncome = driver.getBigDecimal("income");
		BigDecimal preBalance = driver.getBigDecimal("balance");
		String license_num = driver.getStr("license_num");
		String device_id = driver.getStr("device_id");
		String phone = driver.getStr("phone");

		Db.update("update b_user set balance = IFNULL(balance,0)+? where id = ?",
				recharge.get("money"), driverId);
		
		Driver driver1 = Driver.dao.findById(driverId);
		BigDecimal afterBalance = driver1.getBigDecimal("balance");
		BigDecimal afterIncome = driver1.getBigDecimal("income");
		
		recharge.put("before_balance", preBalance);
		recharge.put("after_balance", afterBalance);
		recharge.put("deposit_type", TypeConstant.DepositType.CASH.name());
		recharge.put("deposit_status", TypeConstant.DepositStatus.FINISHED.name());
		recharge.save();
		String company = (String) getSession().getAttribute("company");
		String companyname = (String) getSession().getAttribute("myCompanyName");
		String userName = (String) getSession().getAttribute("userName");
		
		Db.update("insert into b_user_balance_change(b_user_id,payment_time,daymoney,cur_balance,cur_income,before_balance,before_income,license_num,remarks) values(?,now(),?,?,?,?,?,?,?)",
				driverId,recharge.get("money"),afterBalance, afterIncome, preBalance, preIncome, license_num, "充值:"+recharge.getStr("remark"));
		
		Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,pre_amt,after_amt,log_amt,remarks,company,companyname,sys_user_name,create_time) values(?,?,?,?,?,?,?,?,?,?,?)",
				sysUserId,driverId,TypeConstant.OperatorType.DRIVER_BALANCE_DEPOSIT.name(),preBalance,afterBalance,recharge.get("money"),
				TypeConstant.OperatorType.DRIVER_BALANCE_DEPOSIT.getTypeName(),company,companyname,userName,new Date());

		try {
			BigDecimal chargeAmt = recharge.get("money");
			String chargeType = "";
			if(BigDecimal.ZERO.compareTo(chargeAmt) < 0){
				chargeType = "充值";
			}else{
				chargeType = "扣款";
			}
			String content = "您的账号:"+phone+"已成功"+chargeType+"（充值）"+recharge.get("money")+"，"+chargeType+"后余额为："+afterBalance+"。赶快登录看看余额吧！";
			SmsUtil.sendMessage(phone,content,license_num);
			
			PushTokenUtils.sendPush(content, device_id, JpushType.driver_balance_change, new HashMap());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		redirect("/driver");
	}

	public void edit() {
		int driverId = getParaToInt();
		Driver driver = Driver.dao.findById(driverId);
		setAttr("driver", driver);
		render("../recharge/driver_recharge_edit.ftl");
	}

	@Before(Tx.class)
	public void update() {
		Recharge recharge = getModel(Recharge.class);
		int driverId = recharge.getInt("b_user_id");
		int sysUserId = (Integer) getSession().getAttribute("userId");
		
		String remark = getPara("remark");
		
		Driver driver = Driver.dao.findById(driverId);
		BigDecimal preBalance = driver.getBigDecimal("balance");
		BigDecimal preIncome = driver.getBigDecimal("income");
		String license_num = driver.getStr("license_num");
		String device_id = driver.getStr("device_id");
		
		Db.update("update b_user set balance = balance+?,remark=? where id = ?",
				recharge.get("money"),remark, driverId);
		
		Driver driver1 = Driver.dao.findById(driverId);
		BigDecimal afterBalance = driver1.getBigDecimal("balance");
		BigDecimal afterIncome = driver1.getBigDecimal("income");
		String phone = driver.getStr("phone");
		
		String company = (String) getSession().getAttribute("company");
		String companyname = (String) getSession().getAttribute("myCompanyName");
		String userName = (String) getSession().getAttribute("userName");
		
		Db.update("insert into b_user_balance_change(b_user_id,payment_time,daymoney,cur_balance,cur_income,before_balance,before_income,license_num,remarks) values(?,now(),?,?,?,?,?,?,?)",
				driverId,recharge.get("money"),afterBalance, afterIncome, preBalance, preIncome, license_num, remark);
		
		Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,pre_amt,after_amt,log_amt,remarks,company,companyname,sys_user_name,create_time) values(?,?,?,?,?,?,?,?,?,?,?)",
				sysUserId,driverId,TypeConstant.OperatorType.DRIVER_BALANCE_CHANGE.name(),preBalance,afterBalance,recharge.get("money"),
				TypeConstant.OperatorType.DRIVER_BALANCE_CHANGE.getTypeName(),company,companyname,userName,new Date());
		
		
		BigDecimal chargeAmt = recharge.get("money");
		String chargeType = "";
		if(BigDecimal.ZERO.compareTo(chargeAmt) < 0){
			chargeType = "充值";
		}else{
			chargeType = "扣款";
		}
		String content = "您的账号:"+phone+"已成功"+chargeType+"（"+remark+"）"+recharge.get("money")+ "，"+chargeType+"后余额为："+afterBalance+"。赶快登录看看余额吧！";
		//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
		//Db.update(insertMessage,phone,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
		
		SmsUtil.sendMessage(phone,content,license_num);
		
		try {
			PushTokenUtils.sendPush(content, device_id, JpushType.driver_balance_change, new HashMap());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		redirect("/driver");
	}
	
	public void driverChargeDetail(){
		int driverId = getParaToInt("driverId");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		setAttr("driverId", driverId);
		
		String beginDateStr = this.getPara("beginDate");
		String endDateStr = this.getPara("endDate");
		if(beginDateStr == null || endDateStr == null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			setAttr("beginDate", sdf.format(Calendar.getInstance().getTime()));
			setAttr("endDate", sdf.format(Calendar.getInstance().getTime()));
			setAttr("order_type","1");
			render("../recharge/driver_charge_list.ftl");
			return;
		}

		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);
		
		StringBuffer from = new StringBuffer();
		from.append(" from b_user_balance_change a left join (order_detail e) on a.order_id=e.id  ");
		
		String type=getPara("order_type");
		if(!"1".equals(type)){
			setAttr("order_type",type);
			//from .append("");
		}
		else{
			setAttr("order_type","1");
		}
		
		from.append("where a.b_user_id=? and payment_time >= ? and payment_time < ?");
		if(!"1".equals(type)){
			from .append("  and e.order_category_type='"+type+"'");
		}
		/*
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			from.append(" and license_num like '" + company + "%'");
		}*/
		
		from.append(" order by a.id DESC ");
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,e.kilometre,e.order_category_type order_type," +
						" (select name from b_user b where b.id=a.b_user_id) driverName, " +
						" (select job_number from b_user b where b.id=a.b_user_id) jobNumber ",
						from.toString(),driverId,beginDate,endDate);
		
		setAttr("page", page);
		setAttr("beginDate", beginDateStr);
		setAttr("endDate", endDateStr);
		
		render("../recharge/driver_charge_list.ftl");
	}

	public void excel() {
		String job_number = getPara("job_number");
		String realName = getPara("real_name");
		String cellPhone = getPara("cell_phone");
		String beginDateStr = getPara("start_time");
		String endDateStr = getPara("end_time");
		

		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);
		
		String company=(String) getSession().getAttribute("company");
		
//		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		StringBuffer from = new StringBuffer();
		from.append(" from recharge a inner join b_user b on a.b_user_id = b.id left join sys_user c on a.sys_user_id = c.id where 1=1");
		if (StringUtils.isNotBlank(job_number)) {
			from.append(" and b.job_number='" + job_number.toUpperCase() + "'");
		}
		if (StringUtils.isNotBlank(realName)) {
			from.append(" and b.name='" + realName + "'");
		}
		if (StringUtils.isNotBlank(cellPhone)) {
			from.append(" and b.phone='" + cellPhone + "'");
		}
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			from.append(" and b.job_number regexp '" + company + "[0-9]+'");
		}
		if(StringUtils.isNotEmpty(beginDateStr) && StringUtils.isNotEmpty(endDateStr)){
			//from.append(" and a.time >"+beginDateStr+" and a.time<"+endDateStr);
			from.append(" and a.time  between '"+TimeUtil.format(beginDate, "yyyy-MM-dd HH:mm:ss")+"' and '"+TimeUtil.format(endDate, "yyyy-MM-dd HH:mm:ss")+"'");
		}
		from.append(" order by a.id DESC ");
		String sql = "select b.login_name , b.name,b.phone , a.money , a.recharge_type  , a.time , c.real_name as sysUserName"
				+ from.toString();

		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow((short) 0);
		row.createCell(0).setCellValue("真实姓名");
		row.createCell(1).setCellValue("手机号码");
		row.createCell(2).setCellValue("充值金额");
		row.createCell(3).setCellValue("充值类型");
		row.createCell(4).setCellValue("充值时间");

		List<Record> list;

		DecimalFormat df = new DecimalFormat("0.00");
		list = Db.find(sql);
		BigDecimal money = null;
		Timestamp time = null;
		int rechargeType = 0;
		for (int i = 0; i < list.size(); i++) {
			HSSFRow r = sheet.createRow(i + 1);
			Record record = list.get(i);
			r.createCell(0).setCellValue(record.getStr("name"));
			r.createCell(1).setCellValue(record.getStr("phone"));

			money = record.getBigDecimal("money");
			r.createCell(2).setCellValue(df.format(money));

			rechargeType = record.getInt("recharge_type");
			if (rechargeType == 0) {
				r.createCell(3).setCellValue("现金");
			} else if (rechargeType == 1) {
				r.createCell(3).setCellValue("网银");
			} else if (rechargeType == 2) {
				r.createCell(3).setCellValue("支票");
			} else if (rechargeType == 3) {
				r.createCell(3).setCellValue("微信");
			} else {
				r.createCell(3).setCellValue("其他");
			}

			time = record.getTimestamp("time");
			if (time != null) {
				r.createCell(4).setCellValue(
						TimeUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
			} else {
				r.createCell(4).setCellValue("");
			}

		}
		PathUtil.getWebRootPath();
		String fileName = PathUtil.getWebRootPath() + "/excel/"
				+ System.currentTimeMillis() + "_" + new Random().nextLong()
				+ ".xls";
		File f = new File(fileName);
		log.debug("file path:" + f.getAbsolutePath());
		FileOutputStream fOut;
		try {
			fOut = new FileOutputStream(fileName);
			workbook.write(fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			throw new RuntimeException("导出excel失败，请稍后再试", e);
		}
		renderFile(f);
	}

	private Date setTime(Date date, int hour, int minute, int second, int ms) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MILLISECOND, ms);
		date = calendar.getTime();
		return date;
	}
}
